package com.security.manage.apigateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.security.manage.apigateway.model.ResData;
import com.security.manage.apigateway.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthService authService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        HttpHeaders headers = request.getHeaders();
        String uri = request.getURI().getPath();
        if (uri.indexOf("/login")>0||uri.indexOf("/v2/api-docs")>0
                ||uri.indexOf("/file/upload")>0){
            return chain.filter(exchange);
        }
        String token = headers.getFirst("token");
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            ResData resData = new ResData(0,"无访问权限");
            DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONString(resData).getBytes());
            return response.writeWith(Flux.just(wrap));
        }
        String result = authService.checkToken(token);
        JSONObject jsonObject = JSON.parseObject(result);
        Integer status = jsonObject.getInteger("status");
        if (status==1){
            String data = jsonObject.getString("data");
            JSONObject object = JSON.parseObject(data);
            Long userId = object.getLong("userId");
            ServerHttpRequest.Builder mutate = exchange.getRequest().mutate();
            mutate.header("userId", String.valueOf(userId));
            if (StringUtils.isNotEmpty(object.getString("refreshToken"))) {
                mutate.header("refreshToken", "dddd");
            }
            ServerWebExchange build = exchange.mutate().request(mutate.build()).build();
            return chain.filter(build);
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        DataBuffer wrap = response.bufferFactory().wrap(result.getBytes());
        return response.writeWith(Flux.just(wrap));

    }

    @Override
    public int getOrder() {
        return -200;
    }
}
